package JUC;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{
    volatile Map<String, Object> map = new HashMap<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() +
                    "\t正在写入：");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() +
                    "\t写入完成");
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public void get(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() +
                    "\t正在读取：");
            Thread.sleep(200);
            if (map.containsKey(key)){
                System.out.println(Thread.currentThread().getName() +
                        "\t读取到的内容：" + map.get(key));
            }
            System.out.println(Thread.currentThread().getName() +
                    "\t读取完成");
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }

    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache cache = new MyCache();

        for (int i = 0; i < 5; i++) {
            int tempInt = i;
            new Thread(()->{cache.put(tempInt + "", tempInt);}, String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int tempInt = i;
            new Thread(()->{cache.get(tempInt + "");}, String.valueOf(i)).start();
        }
    }

}
